﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Google.GData.Apps;
using System.Threading;

namespace UserAccountsManager
{
    public partial class OknoGlavno : Form
    {
        private OknoLogin login = new OknoLogin();
        private AppsService service;
        private String customerId;
        private OrganizationService organization;
        private AppsExtendedFeed organizationUnits;
        private AppsExtendedFeed organizationUsers;

        public OknoGlavno()
        {
            InitializeComponent();
            statusText.Text = "";
        }

        private void OknoGlavno_Shown(object sender, EventArgs e)
        {
            Connect();
        }

        private void Connect()
        {
            statusText.Text = "Povezujem...";
            do
            {
                if (login.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    try
                    {
                        //processConnect.RunWorkerAsync(login);
                        service = new AppsService(login.Domain, login.Username, login.Password);
                        organization = new OrganizationService(login.Domain, Application.ProductName);
                        organization.setUserCredentials(login.Username, login.Password);
                        customerId = organization.RetrieveCustomerId(login.Domain).Properties[1].Value;
                    }
                    catch (AppsException ex)
                    {
                        MessageBox.Show(ex.Message + "\r\n" + ex.ErrorCode);
                        service = null;
                        organization = null;
                        customerId = "";
                    }
                    catch (Exception ex)
                    {
                        service = null;
                        organization = null;
                        customerId = "";
                        MessageBox.Show(ex.Message);
                    }
                }
                else
                {
                    Application.Exit();
                    return;
                }
            }
            while (service == null || organization == null || customerId == null);
            try
            {
                statusText.Text = "Berem organizacijske skupine...";
                FillOrganizationUnits();
                statusText.Text = "Pripravljen";
            }
            catch (AppsException ex)
            {
                MessageBox.Show(ex.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void processConnect_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                OknoLogin login = (OknoLogin)e.Argument;
                service = new AppsService(login.Domain, login.Username, login.Password);
                organization = new OrganizationService(login.Domain, Application.ProductName);
                organization.setUserCredentials(login.Username, login.Password);
                customerId = organization.RetrieveCustomerId(login.Domain).Properties[1].Value;
            }
            catch (AppsException ex)
            {
                MessageBox.Show(ex.Message + "\r\n" + ex.ErrorCode);
                service = null;
                organization = null;
                customerId = "";
            }
            catch (Exception ex)
            {
                service = null;
                organization = null;
                customerId = "";
                MessageBox.Show(ex.Message);
            }
        }

        private void processConnect_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            try
            {
                statusText.Text = "Berem organizacijske skupine...";
                FillOrganizationUnits();
                statusText.Text = "Pripravljen";
            }
            catch (AppsException ex)
            {
                MessageBox.Show(ex.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        void FillOrganizationUnits()
        {
            try
            {
                treeViewUporabniki.Nodes.Clear();
                TreeNode root = new TreeNode(login.Domain);
                root.Name = "/";
                organizationUnits = organization.RetrieveAllOrganizationUnits(customerId);
                foreach (AppsExtendedEntry entry in organizationUnits.Entries)
                {
                    TreeNode node = new TreeNode(entry.Properties[2].Value);
                    node.Tag = entry;
                    //node.StateImageIndex = 0;
                    node.Name = entry.Properties[3].Value;
                    if (root.Nodes[entry.Properties[1].Value] != null)
                    {
                        root.Nodes[entry.Properties[1].Value].Nodes.Add(node);
                    }
                    else
                    {
                        root.Nodes.Add(node);
                    }
                }
                treeViewUporabniki.Nodes.Add(root);
            }
            catch (AppsException ex)
            {
                MessageBox.Show(ex.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        void FillOrganizationUsers(string path)
        {
            processFillUsers.RunWorkerAsync(path);
        }

        private void processFillUsers_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                statusText.Text = "Berem uporabnike...";
                string path = (string)e.Argument;
                Invoke(new MethodInvoker(delegate { listView1.Items.Clear(); }));
                organizationUsers = organization.RetrieveAllOrganizationUsersByOrgUnit(customerId, path);
                for (int i = 0; i < organizationUsers.Entries.Count; i++)
                {
                    UserEntry user = null;
                    ListViewItem item = null;
                    AppsExtendedEntry entry = (AppsExtendedEntry)organizationUsers.Entries[i];
                    if (checkBoxPodrobnosti.Checked)
                    {
                        user = service.RetrieveUser(entry.Properties[0].Value.Split('@')[0]);
                        item = new ListViewItem(user.Name.GivenName + " " + user.Name.FamilyName);
                        item.SubItems.Add(entry.Properties[0].Value);
                        if (user.Login.Suspended)
                        {
                            item.SubItems.Add("Suspendiran");
                            item.SubItems[1].Tag = new bool();
                            item.SubItems[1].Tag = false;
                            item.ImageIndex = 2;
                        }
                        else
                        {
                            item.SubItems.Add("Aktiven");
                            item.SubItems[1].Tag = new bool();
                            item.SubItems[1].Tag = true;
                            item.ImageIndex = 1;
                        }
                        item.SubItems.Add("");
                        item.SubItems.Add(entry.Properties[1].Value);
                        //item.SubItems.Add(user.Categories[0].Label);
                    }
                    else
                    {
                        item = new ListViewItem(entry.Properties[0].Value.Split('@')[0]);
                        item.SubItems.Add(entry.Properties[0].Value);
                        item.SubItems.Add("");
                        item.SubItems[1].Tag = new bool();
                        item.SubItems[1].Tag = true;
                        item.SubItems.Add("");
                    }
                    Invoke(new MethodInvoker(delegate { listView1.Items.Add(item); }));
                }
            }
            catch (AppsException ex)
            {
                MessageBox.Show(ex.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void processFillUsers_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            statusText.Text = "Pripravljen";
        }

        private void treeViewUporabniki_AfterSelect(object sender, TreeViewEventArgs e)
        {
            try
            {
                FillOrganizationUsers(treeViewUporabniki.SelectedNode.Name);
            }
            catch (AppsException ex)
            {
                MessageBox.Show(ex.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void checkBoxIzberiVse_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBoxIzberiVse.Checked)
            {
                foreach (ListViewItem item in listView1.Items)
                {
                    item.Checked = true;
                }
            }
            else
            {
                foreach (ListViewItem item in listView1.Items)
                {
                    item.Checked = false;
                }
            }
        }

        private void aktivirajUporabnike()
        {
            foreach (ListViewItem item in listView1.CheckedItems)
            {
                if ((bool)item.SubItems[1].Tag == false)
                {
                    service.RestoreUser(item.SubItems[1].Text.Split('@')[0]);
                }
            }
            FillOrganizationUsers(treeViewUporabniki.SelectedNode.Name);
        }

        private void buttonActivate_Click(object sender, EventArgs e)
        {
            aktivirajUporabnike();
        }

        private void suspendirajUporabnike()
        {
            foreach (ListViewItem item in listView1.CheckedItems)
            {
                if ((bool)item.SubItems[1].Tag == true)
                {
                    service.SuspendUser(item.SubItems[1].Text.Split('@')[0]);
                }
            }
            FillOrganizationUsers(treeViewUporabniki.SelectedNode.Name);
        }

        private void buttonSuspend_Click(object sender, EventArgs e)
        {
            suspendirajUporabnike();
        }

        private void listView1_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            for (int i = 0; i < listView1.Items.Count; i++)
            {
                if (listView1.SelectedIndices.Contains(i))
                {
                    listView1.Items[i].Checked = true;
                }
                else
                {
                    listView1.Items[i].Checked = false;
                }
            }
        }

        private void premakniUporabnike()
        {
            OknoPremakni move = new OknoPremakni();
            foreach (AppsExtendedEntry entry in organizationUnits.Entries)
            {
                move.comboBoxSkupina.Items.Add(entry.Properties[2].Value);
            }
            move.usernames.Clear();
            foreach (ListViewItem item in listView1.CheckedItems)
            {
                move.usernames.Add(item.SubItems[1].Text);
            }
            move.label2.Text = treeViewUporabniki.SelectedNode.Text;
            move.selectedNodeText = treeViewUporabniki.SelectedNode.Text;
            move.selectedNodePath = treeViewUporabniki.SelectedNode.Name;
            move.comboBoxSkupina.SelectedIndex = 0;
            if (move.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                processMoveUsers.RunWorkerAsync(move);
            }
        }

        private void buttonPremakni_Click(object sender, EventArgs e)
        {
            premakniUporabnike();
        }

        private void processMoveUsers_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                OknoPremakni move = (OknoPremakni)e.Argument;
                AppsExtendedEntry entry = (AppsExtendedEntry)organizationUnits.Entries[move.comboBoxSkupina.SelectedIndex];
                String newOrgPath = entry.Properties[3].Value;
                int count = move.usernames.Count;
                String timeleft = "";
                for (int i = 0; i < count; i++)
                {
                    DateTime time1 = DateTime.Now;
                    statusText.Text = "Premikam uporabnika " + move.usernames[i] + " iz " + move.selectedNodeText + " v " + entry.Properties[2].Value + ". " + timeleft;
                    organization.UpdateOrganizationUser(customerId, move.usernames[i], newOrgPath, move.selectedNodePath);
                    DateTime time2 = DateTime.Now;
                    timeleft = "Do konca še približno " + ((time2 - time1).Seconds * (count - i)).ToString() + " sekund.";
                }
            }
            catch (AppsException ex)
            {
                MessageBox.Show(ex.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void processMoveUsers_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            statusText.Text = "Pripravljen";
            FillOrganizationUsers(treeViewUporabniki.SelectedNode.Name);
        }

        private void buttonNovoGeslo_Click(object sender, EventArgs e)
        {
            Random r = new Random();
            OknoGesla gesla = new OknoGesla();
            gesla.service = service;
            gesla.domena = login.Domain;
            gesla.organizacijskaEnota = treeViewUporabniki.SelectedNode.Text;
            foreach (ListViewItem item in listView1.CheckedItems)
            {
                String username = item.SubItems[1].Text.Split('@')[0];
                String ime = "";
                String priimek = "";
                if (username.Contains('.'))
                {
                    ime = username.Split('.')[0];
                    priimek = username.Split('.')[1];
                }
                else
                {
                    ime = username;
                    priimek = username;
                }
                ime = char.ToUpper(ime[0]) + ime.Substring(1).ToLower();
                priimek = char.ToUpper(priimek[0]) + priimek.Substring(1).ToLower();
                String email = item.SubItems[1].Text;
                String geslo = "";
                if (ime.Length > 4) geslo = ime.Remove(4);
                else geslo = ime;
                while (geslo.Length < 8) geslo += (r.Next() % 10).ToString();
                gesla.listViewUporabniki.Items.Add(ime + " " + priimek).SubItems.AddRange(new String[] { email, username, geslo });
            }
            gesla.ShowDialog();
        }

        private void vizitkaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            About about = new About();
            about.ShowDialog();
        }

        private void vnosUporabnikovToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OknoVnosUporabnikov vnosUporabnikov = new OknoVnosUporabnikov();
            vnosUporabnikov.domena = login.Domain;
            vnosUporabnikov.ShowDialog();
        }

        private void aktivirajToolStripMenuItem_Click(object sender, EventArgs e)
        {
            aktivirajUporabnike();
        }

        private void suspendirajToolStripMenuItem_Click(object sender, EventArgs e)
        {
            suspendirajUporabnike();
        }

        private void premakniToolStripMenuItem_Click(object sender, EventArgs e)
        {
            premakniUporabnike();
        }

        private void izhodToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
